import React, { useState, useContext } from 'react';
import { Message, Button, Upload, Spin } from 'antd';
import { InboxOutlined } from '@ant-design/icons';

import Drawer from 'components/Drawer';
import service from 'service';
import { HomeContext } from '../context';

const { Dragger } = Upload;

// 账户编辑
const ImportFile = (props) => {
    const { getList } = useContext(HomeContext);
    const [visible, setVisible] = useState(false);
    const [loading, setLoading] = useState(false);

    const toggledHandle = (bool) => {
        setVisible(bool);
    };
    const showHandle = () => {
        toggledHandle(true);
    }
    const cancelHandle = () => {
        toggledHandle(false);
    }

    const uploadProps = {
        name: 'file', // 发到后台的文件参数名
        accept: 'application/json',
        multiple: false, // 是否支持多选文件，ie10+ 支持。开启后按住 ctrl 可选择多个文件	boolean	false
        maxCount: 1, // 限制上传数量。当为 1 时，始终用最新上传的文件代替当前文件	number	-
        // action: '/api/accounts/importJSONFile?token=' + 'Bearer ' + localStorage.getItem('token'), // 当需要token认证时就很麻烦了, 虽然可以通过参数中添加token来实现验证的问题, 但是并不理想
        showUploadList: false,
        beforeUpload: (file, fileList) => {
            const maxSize = 0.5 * 1024 * 1024;
            const exceed = file.size < maxSize;
            if (!exceed) {
                Message.error('上传文件过大,仅支持' + (maxSize / 1024 / 1024) + 'M以内的文件');
            }
            return exceed;
        },
        customRequest: (file, fileList) => { // 通过覆盖默认的上传行为，可以自定义自己的上传实现 (这种方式)
            let formdata
            formdata = new FormData();
            formdata.append('file', file.file);
            setLoading(true);
            service.account.importJSONFile(formdata).then(data => {
                Message.success('上传成功')
            }).finally(() => {
                setLoading(false);
                toggledHandle(false);
                getList();
            })
        }
    };

    return (
        <>
            <Button type="primary" onClick={showHandle}>文件导入</Button>
            <Drawer title="文件导入" visible={visible} onClose={cancelHandle} footer={null}>
                <Spin spinning={loading}>
                    <Dragger {...uploadProps}>
                        <p className="ant-upload-drag-icon">
                            <InboxOutlined />
                        </p>
                        <p className="ant-upload-text">单击或拖动文件到该区域进行上传</p>
                        <p className="ant-upload-hint"></p>
                    </Dragger>
                </Spin>
            </Drawer>
        </>
    )
}

export default ImportFile;